package ru.pbem.olympia.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;

/**
 * User: roman.pavlov
 * Date: 22-Sep-2010
 * Time: 12:42:10
 */
public class RandomAccessListIterator<T> implements RandomAccessIterator<T> {
    private List<T> elements;

    public RandomAccessListIterator(final List<T> elements) {
        if (elements==null){
            throw new IllegalArgumentException("List should not be null");
        }
        this.elements = new ArrayList<T>(elements);
    }

    @Override
    public boolean hasNext() {
        return !elements.isEmpty();
    }

    @SuppressWarnings({"UnsecureRandomNumberGeneration"})
    @Override
    public T next() {
        if (hasNext()) {
            final T next = elements.get(new Random().nextInt(elements.size()));
            remove(next);
            return next;
        } else {
            throw new NoSuchElementException("No such element.");
        }
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Remove is not supported when with random access");
    }

    @Override
    public boolean remove(final T element) {
        return elements.remove(element);
    }
}
